package com.example.administrator.demorecyclerview;

import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

/**
 * Created by Administrator on 2017/12/21.

 */
public class MyEditTextView extends android.support.v7.widget.AppCompatEditText implements TextWatcher, View.OnFocusChangeListener {
    public MyEditTextView(Context context) {
        super(context);
        setOnFocusChangeListener(this);
    }

    public MyEditTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setOnFocusChangeListener(this);
    }

    public MyEditTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setOnFocusChangeListener(this);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        removeTextChangedListener(this);
    }


    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        final MainActivity.MyObject myObject = (MainActivity.MyObject) getTag();
        if (myObject != null) {
            int va = 0;
            try {
                va = Integer.parseInt(s.toString());

            } catch (Exception e) {

            }

            myObject.value = va;
            myObject.listener.onValChanged(va);
        }

    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        Log.i("@@","####:"+ ((MainActivity.MyObject)v.getTag()).value+","+hasFocus);
        if (hasFocus) {
            addTextChangedListener(this);
        } else {
            removeTextChangedListener(this);
        }
    }
}
